package nix.mall.order.service.impl;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import nix.mall.common.pojo.NixMallResult;
import nix.mall.jedis.JedisClient;
import nix.mall.mapper.OrderItemMapper;
import nix.mall.mapper.OrderMapper;
import nix.mall.mapper.OrderShippingMapper;
import nix.mall.order.service.OrderService;
import nix.mall.pojo.OrderInfo;
import nix.mall.pojo.OrderItem;
import nix.mall.pojo.OrderShipping;

/**
 * 订单处理Service
 */
@Service
public class OrderServiceImpl implements OrderService {

	@Autowired
	private OrderMapper orderMapper;
	
	@Autowired
	private OrderItemMapper orderItemMapper;
	
	@Autowired
	private OrderShippingMapper orderShippingMapper;
	
	@Autowired
	private JedisClient jedisClient;
	
	@Value("${ORDER_ID_GEN_KEY}")
	private String ORDER_ID_GEN_KEY;
	
	@Value("${ORDER_ID_BEGIN_VALUE}")
	private String ORDER_ID_BEGIN_VALUE;
	
	@Value("${ORDER_ID_RESET_EXPIRE}")
	private Integer ORDER_ID_RESET_EXPIRE;
	
	@Value("${ORDER_ITEM_ID_GEN_KEY}")
	private String ORDER_ITEM_ID_GEN_KEY;
	
	@Override
	public NixMallResult createOrder(OrderInfo orderInfo) {
		// 生成订单号（使用redis的incr生成）
		String datetime = new SimpleDateFormat("yyyyMMddHHmmss").format(new Date());
		if (!jedisClient.exists(ORDER_ID_GEN_KEY)) {
			// 设置订单号初始值
			jedisClient.set(ORDER_ID_GEN_KEY, ORDER_ID_BEGIN_VALUE);
			jedisClient.expire(ORDER_ID_GEN_KEY, ORDER_ID_RESET_EXPIRE);
		}
		String orderId = datetime + jedisClient.incr(ORDER_ID_GEN_KEY).toString();
		// 补全属性，向订单表插入数据
		orderInfo.setOrderId(orderId);
		orderInfo.setPostFee("0");
		// 状态：1、未付款，2、已付款，3、未发货，4、已发货，5、交易成功，6、交易关闭
		orderInfo.setStatus(1);
		orderInfo.setCreateTime(new Date());
		orderInfo.setUpdateTime(new Date());
		orderMapper.insert(orderInfo);
		// 补全属性，向订单明细表插入数据
		List<OrderItem> orderItems = orderInfo.getOrderItems();
		for (OrderItem orderItem : orderItems) {
			// 使用redis生成id
			String orderItemId = jedisClient.incr(ORDER_ITEM_ID_GEN_KEY).toString();
			orderItem.setId(orderItemId);
			orderItem.setOrderId(orderId);
			orderItemMapper.insert(orderItem);
		}
		// 向订单物流表插入数据
		OrderShipping orderShipping = orderInfo.getOrderShipping();
		orderShipping.setOrderId(orderId);
		orderShipping.setCreated(new Date());
		orderShipping.setUpdated(new Date());
		orderShippingMapper.insert(orderShipping);
		// 返回订单号
		return NixMallResult.ok(orderId);
	}

}
